const express = require("express");
const router = express.Router();
const { success, successWithData, fail } = require("../utils/result");
const { check } = require("express-validator");
const { checkParam } = require("../utils/checkUtils");
const Order = require("../db/model/orderModel");
const OrderItem = require("../db/model/orderItemModel");
const { Op } = require("sequelize");

/**
 * 分页查询接口
 * @api {POST} /order/queryOrderListByPage 分页查询接口
 * @apiDescription 分页查询接口
 * @apiName queryOrderListByPage
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} page=1   页码
 * @apiBody {Number} limit=10   每页条数
 * @apiParamExample {json} Request-Example:
 *     {
 *        "page": 1,
 *        "limit": "10",
 *     }
 * @apiGroup Order
 * @apiVersion 1.0.0
 */
router.post(
  "/order/queryOrderListByPage",
  check("page").not().isEmpty(),
  check("limit").not().isEmpty(),
  async function (req, res) {
    checkParam(req);
    const { page, limit, status, order_code, user_id } = req.body;
    const where = {};
    let offset = (page - 1) * limit;
    if (status >= 0) {
      where["status"] = status * 1;
    }
    if (order_code) {
      where["order_code"] = order_code;
    }
    if (user_id) {
      where["user_id"] = user_id;
    }
    const result = await Order.findAndCountAll({
      limit,
      offset,
      where,
      order: [["created_time", "DESC"]],
    });
    if (result.count > 0) {
      // 查询子订单
      let orderCodes = result.rows.map((order) => order.order_code);
      let orderItems = await OrderItem.findAll({
        where: { order_code: { [Op.in]: orderCodes } },
      });
      if (orderItems && orderItems.length > 0) {
        let map = new Map();
        orderItems.forEach((row) => {
          if (map[row.order_code]) {
            map[row.order_code].push(JSON.parse(JSON.stringify(row)));
          } else {
            let list = [];
            list.push(JSON.parse(JSON.stringify(row)));
            map[row.order_code] = list;
          }
        });
        console.log(map);
        result.rows.forEach((order) => {
          if (map[order.order_code]) {
            order.dataValues.order_items = map[order.order_code];
          }
        });
        console.log(result);
      }
    }
    return res.json(successWithData(result));
  }
);

/**
 * @api {POST} /order/updateStatus 更新订单状态
 * @apiDescription 更新订单状态
 * @apiName updateStatus
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} id=1   主键id
 * @apiBody {Number} status=1   状态 0待付款 1取消 2待发货 3已发货 4已收货 5已完成
 * @apiParamExample {json} Request-Example:
 *     {
 *        "id": 1,
 *        "status": 1
 *     }
 * @apiGroup Order
 * @apiVersion 1.0.0
 */
router.post(
  "/order/updateStatus",
  check("id").not().isEmpty(),
  check("status").not().isEmpty(),
  async function (req, res) {
    checkParam(req);
    const { status, id } = req.body;
    let order = await Order.findByPk(id);
    console.log("当前订单状态：", order.status);
    if (status == 1 && order.status != 0) {
      return res.json(fail("该订单无法取消！"));
    }
    if (status == 2) {
      return res.json(fail("不支持手动触发该状态！"));
    }
    if (status == 3 && order.status != 2) {
      return res.json(fail("该订单状态无法变更为已发货！"));
    }
    if (status == 5 && order.status != 4) {
      return res.json(fail("该订单状态无法变更为已完成！"));
    }
    if (status == 4 && order.status != 3) {
      return res.json(fail("该订单状态无法变更为已收货！"));
    }
    if (status == 3) {
      // todo 保存发货单号，用于查询物流信息
    }

    const result = await Order.update(
      {
        status: req.body.status,
      },
      { where: { id: req.body.id } }
    );
    return res.json(success());
  }
);

module.exports = router;
